package com.warom.sdg.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.warom.sdg.PlcDataAdapter;
import com.warom.sdg.R;

import com.warom.sdg.model.PlcDataEntity;
import com.warom.sdg.repository.PlcDataRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * PLC数据查看界面
 * 用于显示历史采集的PLC数据
 */
public class PlcDataViewActivity extends AppCompatActivity {

    private static final String TAG = "PlcDataViewActivity";
    
    private Spinner spFilterType;
    private EditText etFilterValue;
    private Button btnFilter, btnClearFilter;
    private ListView lvData;
    private TextView tvNoData;
    
    private PlcDataRepository dataRepository;
    private List<PlcDataEntity> dataList = new ArrayList<>();
    private PlcDataAdapter dataAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plc_data_view);
        
        // 设置返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("PLC历史数据");
        }
        
        // 初始化数据仓库
        dataRepository = new PlcDataRepository(this);
        
        // 初始化视图
        initViews();
        
        // 加载数据
        loadAllData();
    }
    
    private void initViews() {
        spFilterType = findViewById(R.id.sp_filter_type);
        etFilterValue = findViewById(R.id.et_filter_value);
        btnFilter = findViewById(R.id.btn_filter);
        btnClearFilter = findViewById(R.id.btn_clear_filter);
        lvData = findViewById(R.id.lv_data);
        tvNoData = findViewById(R.id.tv_no_data);
        
        // 设置过滤类型下拉框
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.filter_types, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spFilterType.setAdapter(adapter);
        
        // 初始化数据适配器
        dataAdapter = new PlcDataAdapter(this, dataList);
        lvData.setAdapter(dataAdapter);
        
        // 设置过滤按钮点击事件
        btnFilter.setOnClickListener(v -> filterData());
        
        // 设置清除过滤按钮点击事件
        btnClearFilter.setOnClickListener(v -> {
            etFilterValue.setText("");
            loadAllData();
        });
    }
    
    private void loadAllData() {
        dataRepository.getAllData(
            // 成功回调
            data -> {
                if (data != null && !data.isEmpty()) {
                    updateDataList(data);
                } else {
                    showNoDataMessage();
                }
            },
            // 错误回调
            errorMessage -> {
                showError("加载数据失败: " + errorMessage);
                showNoDataMessage();
            }
        );
    }
    
    private void filterData() {
        String filterValue = etFilterValue.getText().toString().trim();
        if (TextUtils.isEmpty(filterValue)) {
            showToast("请输入过滤值");
            return;
        }
        
        int filterType = spFilterType.getSelectedItemPosition();
        
        switch (filterType) {
            case 0: // 按名称过滤
                filterByName(filterValue);
                break;
            case 1: // 按地址过滤
                filterByAddress(filterValue);
                break;
            case 2: // 按类型过滤
                filterByType(filterValue);
                break;
            default:
                loadAllData();
                break;
        }
    }
    
    private void filterByName(String name) {
        dataRepository.getDataByName(
            name,
            // 成功回调
            data -> {
                if (data != null && !data.isEmpty()) {
                    updateDataList(data);
                } else {
                    showNoDataMessage();
                }
            },
            // 错误回调
            errorMessage -> {
                showError("过滤数据失败: " + errorMessage);
                showNoDataMessage();
            }
        );
    }
    
    private void filterByAddress(String address) {
        dataRepository.getDataByAddress(
            address,
            // 成功回调
            data -> {
                if (data != null && !data.isEmpty()) {
                    updateDataList(data);
                } else {
                    showNoDataMessage();
                }
            },
            // 错误回调
            errorMessage -> {
                showError("过滤数据失败: " + errorMessage);
                showNoDataMessage();
            }
        );
    }
    
    private void filterByType(String type) {
        dataRepository.getDataByType(
            type,
            // 成功回调
            data -> {
                if (data != null && !data.isEmpty()) {
                    updateDataList(data);
                } else {
                    showNoDataMessage();
                }
            },
            // 错误回调
            errorMessage -> {
                showError("过滤数据失败: " + errorMessage);
                showNoDataMessage();
            }
        );
    }
    
    private void updateDataList(List<PlcDataEntity> data) {
        runOnUiThread(() -> {
            dataList.clear();
            dataList.addAll(data);
            dataAdapter.notifyDataSetChanged();
            
            tvNoData.setVisibility(View.GONE);
            lvData.setVisibility(View.VISIBLE);
        });
    }
    
    private void showNoDataMessage() {
        runOnUiThread(() -> {
            dataList.clear();
            dataAdapter.notifyDataSetChanged();
            
            tvNoData.setVisibility(View.VISIBLE);
            lvData.setVisibility(View.GONE);
        });
    }
    
    private void showError(String message) {
        Log.e(TAG, message);
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }
    
    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 